package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Service
public class FileService {
    private static final Logger log = LoggerFactory.getLogger(FileService.class);

    @Value("${path.root}")
    private String rootPath;
    @Value("${path.prefix.image}")
    private String imgPath;
    @Value("${file.url}")
    private String fileUrl;


    public Response uploadImg(MultipartFile file) {
        String fileName = imgPath + FileUtil.getPathFileName() + ".jpg";
        try {
            File osFile = new File(rootPath + fileName);
            log.info("上传位置:{}", osFile.getAbsolutePath());
            if (!osFile.getParentFile().exists()) {
                osFile.getParentFile().mkdirs();
            }
            file.transferTo(osFile);
        } catch (Exception e) {
            log.error("", e);
            return Response.getError("上传失败！");
        }
        return Response.getSuccess(fileUrl+fileName);
    }

    public String uploadImg1(MultipartFile file) {
        String fileName = imgPath + FileUtil.getPathFileName() + ".jpg";
        try {
            File osFile = new File(rootPath + fileName);
            log.info("上传位置:{}", osFile.getAbsolutePath());
            if (!osFile.getParentFile().exists()) {
                osFile.getParentFile().mkdirs();
            }
            file.transferTo(osFile);
        } catch (Exception e) {
            log.error("", e);
        }
        return fileName;
    }
}
